﻿///<reference path="../../scripts/jquery-1.4.4.min.js" />
///<reference path="../../scripts/kooboo/kooboo.html.js" />

var variationEditIndex = 0;

//EditorForVariation

function EditorForVariation(index) {
    var form = $("#variation-form");
    if (typeof (index) != "undefined") {
        $(form).dialog("option", "title", variation_editTitle);
    }
    else {
        $(form).dialog("option", "title", variation_newTitle);
    }
    $(form).dialog("open");
    switchTab(form.find(".tabs > li:eq(0)"));


    form.find("#variation-valiation-conatiner").empty();

    var webcontrol = form.find(".webcontrol-selector"); //.val("").change();
    var selections = form.find(".variation-form-selections"); //.val("");
    var defaultvalue = form.find(".variation-form-default-value"); //.val("");
    var name = form.find(".variation-form-name"); //.val("");
    var datatype = form.find(".datatype-selector"); //
    var variation = variations[index];

    if (index == undefined) {
        variationEditIndex = variations.length;
    } else {
        variationEditIndex = index;
    }
    if (variation) {
        webcontrol.val(variation.WebControlName).change();
        selections.val(variation.Selections);
        defaultvalue.val(variation.DefaultValues);
        name.val(variation.Name);

        for (var i = 0; i < variation.Rules.length; i++) {
            RenderVariationValiationRule(variation.Rules[i]);
        }
    } else {
        webcontrol.val(webcontrol.find("option:eq(0)").val()).change();
        selections.val("");
        defaultvalue.val("");
        name.val("");

    }

}
//RenderVariation

function RenderVariation(index) {

    var template = $("#variation-container").find("tr[variation-index=" + index + "]:eq(0)");

    if (template.size() == 0) {

        template = $("<tr class='moveable'>"
+ "            <td></td>"
+ "            <td></td>"
+ "            <td>Custom</td>"
+ "            <td class='sort'></td>"
+ "            <td class='action'>"
+ "                <a title='Edit' class='o-icon edit dialog-link variation-edit' href='#variationForm'>Edit</a>"
+ "            </td>"
+ "            <td class='action'>"
+ "                <a title='Remove' class='o-icon remove variation-remove' href='#'>Remove</a>"
+ "            </td>"
+ "</tr>");

        template.attr("variation-index", index);

        template.find(".variation-edit").click(function (e) {
            e.preventDefault();
            EditorForVariation(index);
            return false;
        });

        template.find(".variation-remove").click(function (e) {
            e.preventDefault();
            $(this).parents("tr:eq(0)").remove();
            //variations.splice(index, 1);
            variations[index] = null;
            return false;
        });

        $("#variation-container").append(template);
    }





    var prefix = "Variations[" + index + "]";
    var variation = variations[index];

    var nameColumn = template.find("td:eq(0)");
    nameColumn.html(variation.Name);

    var webControlColumn = template.find("td:eq(1)");
    webControlColumn.html(variation.WebControlName);

    var lastColumn = template.find("td:last");

    lastColumn.find("input").each(function () {
        $(this).remove();
    });

    lastColumn.append(kooboo.html.hidden("Variations.index", index));

    lastColumn.append(kooboo.html.hidden(prefix + ".Id", variation.Id));
    lastColumn.append(kooboo.html.hidden(prefix + ".Name", variation.Name));
    lastColumn.append(kooboo.html.hidden(prefix + ".DataFormat", variation.DataFormat));
    lastColumn.append(kooboo.html.hidden(prefix + ".DefaultValues", variation.DefaultValues));
    lastColumn.append(kooboo.html.hidden(prefix + ".Selections", variation.Selections));
    lastColumn.append(kooboo.html.hidden(prefix + ".Sequence", variation.Sequence).addClass("sequence"));
    lastColumn.append(kooboo.html.hidden(prefix + ".WebControl.Name", variation.WebControlName));

    for (var i = 0; i < variation.Rules.length; i++) {
        var rule = variation.Rules[i];

        var prefix_Rule = prefix + ".ValidationRules[" + i + "]";

        lastColumn.append(kooboo.html.hidden(prefix + ".ValidationRules.index", i));
        lastColumn.append(kooboo.html.hidden(prefix_Rule + ".Id", rule.Id));
        lastColumn.append(kooboo.html.hidden(prefix_Rule + ".Validator.Name", rule.ValidatorName));
        lastColumn.append(kooboo.html.hidden(prefix_Rule + ".ErrorMessage", rule.ErrorMessage));


        for (var n = 0; n < rule.Parameters.length; n++) {
            var para = rule.Parameters[n];
            var prefix_Para = prefix_Rule + ".Parameters[" + n + "]";
            lastColumn.append(kooboo.html.hidden(prefix_Rule + ".Parameters.index", n));
            lastColumn.append(kooboo.html.hidden(prefix_Para + ".Name", para.Name));
            lastColumn.append(kooboo.html.hidden(prefix_Para + ".Value", para.Value));
        }


    }


    SortVariations();

}

//RenderVariationValiationRule

function RenderVariationValiationRule(rule) {

    var template = $("<tbody>"
+ " <tr>"
+ "     <th>"
+ "         <label>Type</label>"
+ "          <input type=hidden name=rule-id></input>"
+ "     </th>"
+ "     <td>"
+ "         <select name='rule-validator' class='medium'></select>"
+ "      </td>"
+ " </tr> "
+ " <tr> "
+ "       <th>"
+ "           <label>Error message</label>"
+ "       </th>"
+ "       <td>"
+ "           <input type='text' name='rule-errormessage' class='medium' />"
+ "           <a href='#' class='o-icon remove' title='Remove'>Remove</a>"
+ "       </td>"
+ "   </tr>"
+ "</tbody>");

    var select = template.find("select");
    var validator;
    for (var i = 0; i < validators.length; i++) {
        var item = validators[i];
        var option = kooboo.html.option(item.Name, item.Name);
        select.append(option);
        if (rule) {
            if (rule.ValidatorName == item.Name) {
                validator = item;
                option.attr("selected", true);
            } else {
                option.attr("selected", false);
            }
        }
    }

    if (validator == null) {
        validator = validators[0];
    }

    RenderVariationValidationRuleParameters(select, rule, validator);

    if (rule) {
        template.find("input[name=rule-errormessage]").val(rule.ErrorMessage);
        template.find("input[name=rule-id]").val(rule.Id);
    } else {
        template.find("input[name=rule-id]").val(-1);
    }


    select.change(function () {
        var selector = $(this);
        var selected_valiator_name = selector.val();
        var validator = null;
        for (var i = 0; i < validators.length; i++) {
            var item = validators[i];
            if (item.Name == selected_valiator_name) {
                validator = item;
            }
        }
        RenderVariationValidationRuleParameters($(this), rule, validator);
    });

    template.find(".remove").click(function (e) {
        e.preventDefault();
        $(this).parents("tbody:eq(0)").remove();
        return false;
    });

    $("#variation-valiation-conatiner").append(template);


}

function RenderVariationValidationRuleParameters(select, rule, validator) {
    if (validator) {
        var parent = select.parent();
        parent.find("input").each(function (index, item) {
            $(item).remove();
        });

        parent.find("label").each(function (index, item) {
            $(item).remove();
        });
        for (var i = 0; i < validator.Parameters.length; i++) {
            var para = validator.Parameters[i];
            paraValue = "";

            if (rule) {
                for (var n = 0; n < rule.Parameters.length; n++) {
                    var item = rule.Parameters[n];
                    if (item.Name == para.Name) {
                        paraValue = item.Value;
                        break;
                    }
                }
            }

            var label = kooboo.html.label(para.Name);
            var input = kooboo.html.textbox(para.Name, paraValue).addClass("short").addClass("rule-para");
            parent.append(label).append(input);

        }
    }
}

// UpdateVariationValidationRule 

function UpdateVariationValidationRule() {
    var variation = variations[variationEditIndex];
    if (!variation) {
        variation = {};
        variation.Id = -1;

        variations[variationEditIndex] = variation;
    }

    var form = $("#variation-form");

    variation.Name = form.find(".variation-form-name").val();
    variation.DataFormat = form.find(".datatype-selector").val();
    variation.DefaultValues = form.find(".variation-form-default-value").val();
    variation.Selections = form.find(".variation-form-selections").val();
    variation.WebControlName = form.find(".webcontrol-selector").val();

    variation.Rules = [];

    form.find("#variation-valiation-conatiner >tbody").each(function (index, item) {
        var $item = $(item);
        var rule = {};
        rule.Id = parseInt($item.find("input[name=rule-id]").val());
        rule.ValidatorName = $item.find("select[name=rule-validator]").val();
        rule.ErrorMessage = $item.find("input[name=rule-errormessage]").val();

        rule.Parameters = [];

        $item.find(".rule-para").each(function (paraIndex, paraInput) {
            var input = $(paraInput);
            var para = {};
            para.Name = input.attr("name");
            para.Value = input.val();

            rule.Parameters[paraIndex] = para;
        });

        variation.Rules.push(rule);

    });

    $(form).dialog("close");
    //debugger;
    RenderVariation(variationEditIndex);

    variationEditIndex = 0;

}

// Evnets 
$(function () {
    for (var i = 0; i < variations.length; i++) {
        var variation = variations[i];
        if (variation) {
            RenderVariation(i);
        }
    }



    $(".variation-add").click(function (e) {
        e.preventDefault();
        EditorForVariation();
        return false;
    });

    $(".variation-validation-rule-add").click(function (e) {
        e.preventDefault();
        RenderVariationValiationRule(null);
        return false;
    });

    $(".variation-validation-rule-update").click(function (e) {
        e.preventDefault();
        UpdateVariationValidationRule();
        return false;
    });

    $('#variation-container a.arrow').click(function () {
        source = $(this).parents('tr.moveable');
        if ($(this).hasClass('up')) {
            target = source.prev();
            target.before(source);
            SortVariations();
        }
        else if ($(this).hasClass('down')) {
            target = source.next();
            target.after(source);
            SortVariations();
        }
    })

    SortVariations();

});

//Sort arrow init
function SortVariations() {
    $('#variation-container > .moveable').each(function (index, item) {
        //debugger;
        $(this).find(".sequence").val(index);
        target = $(this).children('td.sort');
        var parent = $(this).parent();
        if (!($(this).prev().hasClass('moveable')) && $(this).next().hasClass('moveable')) {
            arrows = parent.find('.move-arrow .move-first').children().clone(true);
            target.empty();
            target.append(arrows);
        }
        else if ($(this).prev().hasClass('moveable') && !($(this).next().hasClass('moveable'))) {
            arrows = parent.find('.move-arrow .move-last').children().clone(true);
            target.empty();
            target.append(arrows);
        }
        else if ($(this).next().hasClass('moveable') && $(this).prev().hasClass('moveable')) {
            arrows = parent.find('.move-arrow .move-normal').children().clone(true);
            target.empty();
            target.append(arrows);
        }
    });
}
